import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getSignalCollectionList, 
  getSignalStats, 
  deleteSignalCollection, 
  batchDeleteSignalCollections,
  getSignalCollectionDetail,
  addRandomSignalData
} from '../apis/signal.js'

export function useSignalMonitor() {
  // 响应式数据
  const loading = ref(false)
  const signalList = ref([])
  const selectedRows = ref([])
  const total = ref(0)
  const stats = ref({})
  const latestSignal = ref(null)
  const detailDialogVisible = ref(false)
  const currentSignal = ref(null)

  // 查询参数
  const queryParams = reactive({
    page: 1,
    size: 10,
    deviceId: '',
    startTime: '',
    endTime: ''
  })

  // 获取信号数据列表
  const fetchSignalList = async () => {
    loading.value = true
    try {
      const response = await getSignalCollectionList(queryParams)
      if (response.code === 200) {
        signalList.value = response.data.records
        total.value = response.data.total
      } else {
        ElMessage.error('获取信号数据失败')
      }
    } catch (error) {
      ElMessage.error('获取信号数据失败')
      console.error('Error fetching signal list:', error)
    } finally {
      loading.value = false
    }
  }

  // 获取统计信息
  const fetchStats = async () => {
    try {
      const response = await getSignalStats()
      if (response.code === 200) {
        stats.value = response.data
        latestSignal.value = response.data.latest
      }
    } catch (error) {
      console.error('Error fetching stats:', error)
    }
  }

  // 搜索
  const handleSearch = () => {
    queryParams.page = 1
    fetchSignalList()
  }

  // 重置搜索条件
  const handleReset = () => {
    Object.assign(queryParams, {
      page: 1,
      size: 10,
      deviceId: '',
      startTime: '',
      endTime: ''
    })
    fetchSignalList()
  }

  // 刷新数据
  const handleRefresh = async () => {
    try {
      const response = await addRandomSignalData(10)
      if (response.code === 200) {
        ElMessage.success(response.data)
      } else {
        ElMessage.error('采集数据失败')
      }
    } catch (error) {
      ElMessage.error('采集数据失败')
      console.error('Error adding random signal data:', error)
    }
    
    // 刷新列表和统计信息
    fetchSignalList()
    fetchStats()
  }

  // 表格选择变化
  const handleSelectionChange = (selection) => {
    selectedRows.value = selection.map(item => item.id)
  }

  // 分页大小变化
  const handleSizeChange = (size) => {
    queryParams.size = size
    queryParams.page = 1
    fetchSignalList()
  }

  // 当前页变化
  const handleCurrentChange = (page) => {
    queryParams.page = page
    fetchSignalList()
  }

  // 查看详情
  const handleViewDetail = async (row) => {
    try {
      const response = await getSignalCollectionDetail(row.id)
      if (response.code === 200) {
        currentSignal.value = response.data
        detailDialogVisible.value = true
      }
    } catch (error) {
      ElMessage.error('获取详情失败')
      console.error('Error fetching signal detail:', error)
    }
  }

  // 删除单条记录
  const handleDelete = async (row) => {
    try {
      await ElMessageBox.confirm('确定删除这条信号记录吗？', '提示', {
        type: 'warning'
      })
      
      const response = await deleteSignalCollection(row.id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        fetchSignalList()
        fetchStats()
      } else {
        ElMessage.error('删除失败')
      }
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    }
  }

  // 批量删除
  const handleBatchDelete = async (ids) => {
    if (ids.length === 0) {
      ElMessage.warning('请选择要删除的记录')
      return
    }

    try {
      await ElMessageBox.confirm('确定删除选中的信号记录吗？', '提示', {
        type: 'warning'
      })
      
      const response = await batchDeleteSignalCollections(ids)
      if (response.code === 200) {
        ElMessage.success('批量删除成功')
        selectedRows.value = []
        fetchSignalList()
        fetchStats()
      } else {
        ElMessage.error('批量删除失败')
      }
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('批量删除失败')
      }
    }
  }

  // 格式化时间
  const formatTime = (time) => {
    if (!time) return '--'
    return new Date(time).toLocaleString('zh-CN')
  }

  // 获取信号强度类型
  const getSignalStrengthType = (strength) => {
    if (strength >= -70) return 'success'
    if (strength >= -85) return 'warning'
    return 'danger'
  }

  // 获取丢包率类型
  const getPacketLossType = (loss) => {
    if (loss <= 1) return 'success'
    if (loss <= 3) return 'warning'
    return 'danger'
  }

  // 初始化数据
  const initData = () => {
    fetchSignalList()
    fetchStats()
  }

  // 组件挂载时加载数据
  onMounted(() => {
    initData()
  })

  return {
    // 响应式数据
    loading,
    signalList,
    selectedRows,
    total,
    stats,
    latestSignal,
    detailDialogVisible,
    currentSignal,
    queryParams,
    
    // 方法
    handleSearch,
    handleReset,
    handleRefresh,
    handleSelectionChange,
    handleSizeChange,
    handleCurrentChange,
    handleViewDetail,
    handleDelete,
    handleBatchDelete,
    formatTime,
    getSignalStrengthType,
    getPacketLossType,
    initData
  }
}